<template>
	<view class="content" id="chat">
		<!-- <cu-custom bgColor="bg-white" :isBack="true"><block slot="content">{{receiver.name?receiver.name:'客服平台'}}</block></cu-custom> -->
		<cu-custom bgColor="bg-white" :isBack="true">
			<block slot="content">
				<view class="flex-sub title_line_2 " style="height: 40px;">{{receiver.name?receiver.name:'客服平台'}}</view>
			</block>
		</cu-custom>
		<view class="content-box" @touchstart="touchstart" id="content-box" :class="{'content-showfn':showFunBtn}" >
			<view class="content-box-loading" v-if="!loading"><u-loading mode="flower"></u-loading></view>
			<view class="flex padding radius12 overHidden bg-white margin-left-sm margin-right-sm" v-if="izSendGoods">
				<image class="goodsImg radius12" v-if="serviceGoods.goods_image" :src="serviceGoods.goods_image" mode="aspectFill"></image>
				<view class="margin-left flex-direction flex-1 justify-between" style="height: 180rpx;display: flex; flex-direction: column;">
					<view>
						<view class="text-333 text-df text-fw500 ttit">{{serviceGoods.goods_name || ''}}</view>
						<view class="text-theme text-sm" v-if="serviceGoods.goods_price">
							￥{{serviceGoods.goods_price | formatPrice}}
						</view>
					</view>
					<view class="flex-1 flex justify-end align-end">
						<view @tap="clickGrid(2)" class="" style="width:136rpx;height:46rpx;background:rgba(241,133,75,1);border-radius:10rpx;color: #FFFFFF;size: 18rpx;text-align: center;line-height: 46rpx;">发给客服</view>
					</view>
				</view>
			</view>
			<view class="message" v-for="(item, index) in messageList" :key="index" :id="`msg-${item.hasBeenSentId}`">
				<view class="flex justify-center align-center">
					<text class="text-999 text-sm">{{item.create_time | unixToDate}}</text>
				</view>
				<view class="message-item margin-top" :class="item.receive_person_type!=='MEMBER' ? 'right' : 'left'">
					<image class="img" :src="userInfo.face" mode="" @tap="linkToBusinessCard()"></image>
					<view class="content" v-if="item.content_type===1">{{ item.content }}</view>
					<!-- contentType = 2 商品 -->
					<view class="content contentType2" :class="[{ 'content-type-right': item.content_type===3 }]"
						v-if="item.content_type == 3">
						<image :src="item.content.goodsImage" style="width: 230rpx;height: 230rpx;" mode="aspectFill"></image>
						<view class="" style="width: 230rpx;">
							<view class="margin-top-sm" style="width: 100%;color: #CB1414;size:24px;">
								￥{{ item.content.goodsPrice| formatPrice}}
							</view>
							<view class="" style="color: #333333;size:24px;">
								{{ item.content.goodsName }}
							</view>
						</view>
					</view>
					<!-- contentType = 3 图片 -->
					<view class="content contentType3" v-if="item.content_type == 2" @tap="viewImg([item.content])">
						<image :src="item.content" class="img" mode="widthFix"></image>
					</view>
				</view>
			</view> 
		</view>
		<!-- 底部聊天输入框 -->
		<view class="input-box" :class="{'input-box-mpInputMargin': mpInputMargin }">
			<view class="input-box-flex">
				<view class="cuIcon-add text-333 text-lg  margin-right" style="width: 50rpx;color: #FFF;height: 50rpx;font-size: 50rpx;" @tap="switchFun"></view>
				<view class="input-box-flex-grow"> 
					<input
						type="text"
						class="content"
						id="input"
						v-model="content"
						:hold-keyboard="true"
						:confirm-type="'send'"
						:confirm-hold="true"
						placeholder-style="color:#DDDDDD;"
						:cursor-spacing="10"
						@confirm="sendMsg"
					/>
				</view>
				<!-- 功能性按钮 -->
				<button class="btn" type="primary" size="mini" @touchend.prevent="sendMsg">发送</button>
			</view>
			<view class="fun-box" :class="{'show-fun-box':showFunBtn}">
				<view style="display: flex;">
					<view style="padding: 20rpx 30rpx 20rpx 30rpx;align-items: center;" hover-class="contentType2-hover-class"  v-for="(item, index) in funList" :index="index" :key="index" @click="clickGrid(3)" bg-color="#eaeaea">
						<image style="width: 55rpx;height: 50rpx;" :src="item.icon"></image>
						<view style="size: 24rpx;color: #333333;">{{ item.title }}</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { api, api_model } from '@/ui-domain'
	import * as API_Customer from '@/api/customer-service.js.js'
	var sotk = null;
	var socketOpen = false;
	// var wsbasePath = "ws://192.168.100.190:6002";
	// var wsbasePath = "ws://192.168.1.110:6002";
	var wsbasePath = "wss://chat.chinalianjiu.com/wss/";
	let timestamp = parseInt(new Date().getTime() / 1000)
	export default {
		data() {
			return {
				fromUserInfo: {},
				formData: {
					content: '',
					limit: 15,
					index: 1
				},
				content:'', // 文本消息
				messageList: [],
				loading: true, //标识是否正在获取数据
				imgHeight: '1000px',
				mpInputMargin: false, //适配微信小程序 底部输入框高度被顶起的问题
				canSend:true, //是否可以发送
				PointY:0, //坐标位置
				showFunBtn:false, //是否展示功能型按钮
				funList: [
					// { icon:require('@/static/images/chat/camera.png'),title:"照片",uploadType:["album"] },
					// { icon:require('@/static/images/chat/album.png'),title:"拍摄",uploadType:["camera"] },
					{ icon:require('@/static/images/chat/goods.png'),title:"宝贝",uploadType:["camera"] },
				],
				userInfo:uni.getStorageSync('userInfo'),
				serviceGoods:uni.getStorageSync('customerServiceInfo').goods || {},
				izSendGoods:uni.getStorageSync('customerServiceInfo').goods?true:false,
				shop_id:uni.getStorageSync('shop').shop_id,
				receiver:{},
				params:{
					page_no:1,
					page_size:20
				},
				type:1,
				sendTime:30000,
				izChangeGoods:0,
				izSendImg:false,
				timestamp:timestamp,
			};
		},
		onBackPress() {
			this.closeWebsocket()
		},
		beforeDestroy() {
			this.closeWebsocket()
		},
		methods: {
			//拼接消息 处理滚动
			async joinData() {
				if (!this.loading) {
					//如果没有获取数据 即loading为false时，return 避免用户重复上拉触发加载
					return;
				}
				this.loading = false;
			},
			// //处理滚动
			// bindScroll(sel, duration = 0) {
			// 	const query = uni.createSelectorQuery().in(this);
			// 	query.select(sel)
			// 		.boundingClientRect(data => {
			// 			uni.pageScrollTo({
			// 				scrollTop: data && data.top - 40,
			// 				duration
			// 			});
			// 		}).exec();
			// },
			pageScrollToBottomn() {
				wx.createSelectorQuery().select('#chat').boundingClientRect(rect =>{
					wx.pageScrollTo({
				        scrollTop: rect.bottom,
						duration: 300
					})
				}).exec()
			},
			//切换功能性按钮
			switchFun(){
				this.chatType = 'keyboard'
				this.showFunBtn = !this.showFunBtn;
				uni.hideKeyboard()
			},
			//发送消息
			sendMsg() {
				this.type = 1
				var content = this.content.trim()
				let tips = '不能发送空白消息'
				if (content.length <= 0) {
					uni.showToast({
						icon:'none',
						title:tips,
						duration:2000
					})
				  return false
				}else{
					this.chatData(content)
					this.content = ''
					// this.getChatRecordInfo()
					this.$nextTick(() => {
						this.content = '';
						// uni.pageScrollTo({
						// 	scrollTop: 99999,
						// 	duration: 100
						// });
						if(this.showFunBtn){
							this.showFunBtn = false;
						}
						
					});
				}
			},
			//用户触摸屏幕的时候隐藏键盘
			touchstart() {
				uni.hideKeyboard();
			},
			// userid 用户id
			linkToBusinessCard(userId) {
				this.$u.route({
					url: 'pages/businessCard/businessCard',
					params: {
						userId
					}
				});
			},
			//关闭动画
			closeAnmition() {
				const hasBeenSentId = this.Audio.hasBeenSentId;
				const item = this.messageList.find(it => it.hasBeenSentId == hasBeenSentId);
				item.anmitionPlay = false;
			},
			//点击宫格时触发
			clickGrid(index){
				if(index == 0){
					this.type = 2
					this.chooseImage(['album'])
				}else if(index == 1){
					this.type = 2
					this.chooseImage(['camera'])
				}else if(index==2){
					this.type = 3
					this.toCustomerService()
				}else if(index===3){
					this.showFunBtn = false;
					uni.navigateTo({
						url:'./chatGoodsList?izChangeGoods='+this.izChangeGoods
					})
				}
			},
			toCustomerService() {
			    // this.isSend = false
			    // this.type = 3
				let serviceGoods = this.serviceGoods
				if(this.izSendGoods){
					console.log('123123')
					if(this.serviceGoods.goods_id){
						var data = {
						  send_person_id: this.userInfo.uid,
						  content_type: this.type,
						  create_time: parseInt(new Date().getTime() / 1000),
						  is_read: 1,
						  receive_person_id: this.receiver.member_id,
						  receive_person_name: this.receiver.name,
						  send_person_name: this.userInfo.nickname,
						  content: {
						    goodsId: serviceGoods.goods_id,
						    goodsImage: serviceGoods.goods_image,
						    goodsName: serviceGoods.goods_name,
						    goodsPrice: serviceGoods.goods_price,
						    sendTag: true
						  },
						  send_person_type: 'MEMBER',
						  receive_person_type: this.receiver.type,
						  receive_shop_id: this.receiver.member_id,
						  send_shop_id: this.receiver.shop_id
						}
						// this.messageList.push(data)
						// this.izSendImg = true
						this.chatData(JSON.stringify(data.content))  
					}
				} 
			},
			chatData(content) {
			    if (socketOpen) {
			      var data = {
			        member_id: this.userInfo.uid,
			        token: uni.getStorageSync('token'),
			        type: 'SINGLE_SENDING',
			        chat_record_vo: {
			          send_person_id:this.userInfo.uid,
			          content_type: this.type,
			          create_time:parseInt(new Date().getTime() / 1000),
			          is_read: 1,
			          receive_person_id: this.receiver.member_id,
			          receive_person_name: this.receiver.name,
			          send_person_name: this.userInfo.nickname,
			          content,
			          send_person_type: 'MEMBER',
			          receive_person_type: this.receiver.type,
			          receive_shop_id: this.receiver.shop_id,
			          send_shop_id: ''
			        }
			      }
			      // 如果是普通消息我就加进去
			      // if (this.type == 1) {
			      //   // this.messageList.push(data.chat_record_vo)
			      // } else {
			      // }
			      this.sendSocketMessage(data)
				  this.pageScrollToBottomn()
				  
			    } else {
			      this.$message.error('Websocket连接没有开启')
			    }   
				this.getChatRecordInfo()
			},
			//发送图片
			chooseImage(sourceType){
				uni.chooseImage({
					sourceType,
					sizeType:['compressed'], 
					success:res=>{ 
						this.showFunBtn = false;
						for(let i = 0;i<res.tempFilePaths.length;i++){
							const params = {
								content_type: 3,
								content: res.tempFilePaths[i],
							};
							this.chatData(params.content)
						}
					}
				})
			},
			//查看大图
			viewImg(imgList){
				uni.previewImage({
					urls: imgList,
					// #ifndef MP-WEIXIN
					indicator: 'number'
					// #endif
				});
			},
			webSocketStart(){
			    sotk = wx.connectSocket({
			      // url: 'wss://yantianfeng.com:2000',
				  url:wsbasePath,
			      header: { 'content-type': 'application/x-www-form-urlencoded' },
			      method: "POST",
			      success: res => {
			        console.log('小程序连接成功：', res);
					let actions = {
					  member_id: this.userInfo.uid,
					  token: uni.getStorageSync('token'),
					  type: 'REGISTER'            
					}
					this.sendSocketMessage(actions)
					setInterval(()=>{
						this.sendSocketMessage(actions)
					},this.sendTime)
			      },
			      fail: err => {
			        console.log('出现错误啦！！' + err);
			        wx.showToast({
			          title: '网络异常！',
			        })
			      }
			    })
			    this.webSokcketMethods();
			},
			//监听指令
			  webSokcketMethods(e){
			    let that = this;
				let data =  null
			    sotk.onOpen(res => {
			      socketOpen = true;
				  // data = this.getMessageData();
			      console.log('监听 WebSocket 连接打开事件。', res,data);
				  
			    })
			    sotk.onClose(onClose => {
			      console.log('监听 WebSocket 连接关闭事件。', onClose)
			      socketOpen = false;
			    })
			    sotk.onError(onError => {
			      console.log('监听 WebSocket 错误。错误信息', onError)
			      socketOpen = false
				  this.closeWebsocket()
			    })
			
			    sotk.onMessage(onMessage => {
			      var data = JSON.parse(onMessage);
			      console.log('监听WebSocket接受到服务器的消息事件。服务器返回的消息',data);
			    })
			  },
			
			//发送消息
			  sendSocketMessage(msg) {
			    let that = this;
			    if (socketOpen){
			      console.log('通过 WebSocket 连接发送数据', JSON.stringify(msg))
			      sotk.send({
			        data: JSON.stringify(msg)
			      }, function (res) {
			        console.log('已发送', res)
					
			      })
			    }
			  },
			 //关闭连接
			  closeWebsocket(str){
			    if (socketOpen) {
			      sotk.close(
			        {
			          code: "1000",
			          reason: str,
			          success: function () {
			            console.log("成功关闭websocket连接");
			          }
			        }
			      )
			    }
			  },
			sortNumber(a, b) {
			    if (a.create_time < b.create_time) {
			        return -1
			    }      
			},  
			getReceiverInfo(){
			    API_Customer.getReceiver(this.shop_id).then(res =>{
			      if(res.code === '0000'){
			        this.receiver = res.result
			        this.getChatRecordInfo()
			      }
			      console.log(this.receiver)
			    }).catch(res => {
			      console.log(res)
			      this.$message.error(res)
			    })        
			},
			getChatRecordInfo() {
				let userInfo = this.userInfo
			    let params1 = {
			      user_id: this.userInfo.uid,
			      user_type: 'MEMBER',
			      friend_id: this.receiver.member_id,
			      friend_shop_id: this.receiver.shop_id,
			      friend_type: this.receiver.type,
			      page_no: this.params.page_no,
			      page_size: this.params.page_size
			    }
			    setTimeout(()=> {
					API_Customer.getRecordList(params1).then(res =>{
					  console.log('获取列表',res)
					  if (res.data_total&&res.data_total == 0) {
					      return
					  }
					  this.messageList = []
					  res.data.map(item => {
					    if (item.content_type == 3) {
					      item.content = JSON.parse(item.content)
					    }
					    this.messageList.push(item)
					    this.messageList.sort(this.sortNumber)
					  })
					})   
				},300)   
			},
		},
		onPageScroll(e) {
			if (e.scrollTop) {
				this.joinData();
			}
		},
		//返回按钮事件
		onBackPress(e) {
			//以下内容对h5不生效
			//--所以如果用浏览器自带的返回按钮进行返回的时候页面不会重定向 正在寻找合适的解决方案
			// this.$u.route({
			// 	type: 'switchTab',
			// 	url: 'pages/home/home'
			// });
			return true;
		},
		//开始webSocket
		
		onLoad(info) {
			// { messageId,fromUserName,fromUserHeadImg } = info
			let userInfo = uni.getStorageSync('userInfo')
			this.getReceiverInfo()
			this.webSocketStart()
		},
		onShow() {
			let now_serviceGoods = uni.getStorageSync('customerServiceInfo').goods 
			console.log('now_serviceGoods',now_serviceGoods)
			if(now_serviceGoods){
				if(now_serviceGoods.goods_id){
					if(now_serviceGoods.goods_id == this.serviceGoods.goods_id){
						return
					}else{
						this.serviceGoods = now_serviceGoods
						this.clickGrid(2)
					}
				}
			}
				
		},
		onReady() {
			//自定义返回按钮 因为原生的返回按钮不可阻止默认事件
			// #ifdef H5
			const icon = document.getElementsByClassName('uni-page-head-btn')[0];
			icon.style.display = 'none';
			// #endif
	
			uni.setNavigationBarTitle({
				title: this.fromUserInfo.fromUserName
			});
			this.joinData();
			uni.getSystemInfo({
				success: res => {
					this.imgHeight = res.windowHeight + 'px';
				}
			});
			uni.onKeyboardHeightChange(res => {
				if (res.height == 0) {
					// #ifdef MP-WEIXIN
					this.mpInputMargin = false;
					// #endif
				}else{
					this.showFunBtn = false;
				}
			});
		},
	};
</script>
	
<style lang="scss" scoped>
	@import '../../../common/styles/index.scss';
	@import '../../../common/styles/theme.scss';
	.select-hover-class{ //首页导航栏按钮
		background-color: $uni-color-subtitle !important;
	}
	.message-hover-class{ //评论区 点击
		background-color: $uni-bg-color-hover !important;
	}
	.contentType2-hover-class{ //语音信息点击
		background-color: #c7c6c6 !important;
	}
	.contentType2{
			 
	}
	image{
		will-change: transform;
	}
	.u-actionsheet-cancel,
	.u-action-sheet-itemz{
		font-size: 28rpx !important;
	} 
	/deep/.cu-custom .cu-bar .content {
	 	width: calc(100% - 200rpx);
		text-align: left;
		margin-left: 40rpx;
	}
	/deep/.cu-bar .action:first-child {
		margin-left: 20rpx;
	}
	/deep/.cu-bar .content {
		right: 150rpx;
	}
</style>
	